import axios from 'axios'
import { Message, MessageBox, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // 定义全局不显示加载页面的接口
  const strReg = /\/lsp\/vagueSelectLsp|\/add\/user|\/carrier\/usableTrailer|\/driver\/usableCarrier/g
  if (!strReg.test(config.url)) {
    window.LoadingObj = Loading.service({
      lock: true,
      text: 'Loading...',
      spinner: 'el-icon-loading',
      background: 'rgba(225, 225, 225, 0.7)'
    })
  }
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['Authorization'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  /**
  * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
  * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
  */
  response => {
    /**
     * code为非0是抛错 可结合自己业务进行修改
     */
    const res = response.data
    window.LoadingObj.close()
    console.log('拦截HTTP请求返回数据', res)
    if (res.code !== 0) {
      if (res.code === -1 || res.code === 10004) {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      } else if (res.code === 10001 || res.code === 10002) {
        // 10001:非法的token; 10002:Token 过期了;
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (res.code === 50000) {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        setTimeout(function() {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        }, 3000)
      }
      return Promise.reject('error')
    } else if (res.code === 0) {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: '发生请求错误',
      type: 'error',
      duration: 5 * 1000
    })
    window.LoadingObj.close()
    return Promise.reject(error)
  })

export default service
